# 公用函数
#
#
#
import hashlib
import os
import re
import winreg


def find_word_exe_path():
    # 定义Word的注册表路径
    word_reg_path = r'Software\Microsoft\Office'
    # 定义Word版本对应的子键
    word_versions = ['14.0', '15.0', '16.0', '17.0', '18.0', '19.0', '20.0']

    # 尝试不同的Word版本
    for version in word_versions:
        try:
            # 打开注册表项
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, word_reg_path + '\\' + version + r'\Word\InstallRoot', 0,
                                winreg.KEY_READ) as key:
                # 读取默认值，这通常是Word的安装路径
                install_path = winreg.QueryValueEx(key, "Path")[0]
                # Word的可执行文件名
                word_exe = r'WINWORD.EXE'
                # 完整的Word可执行文件路径
                word_exe_path = install_path + word_exe
                # 检查文件是否存在
                if os.path.isfile(word_exe_path):
                    return word_exe_path
        except FileNotFoundError:
            # 如果找不到注册表项，忽略异常并继续尝试
            continue
    # 如果所有版本都尝试过了还是没找到，返回None
    return None


def get_desktop_path_from_registry():
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                            r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders") as key:
            desktop_path, _ = winreg.QueryValueEx(key, 'Desktop')
        return desktop_path
    except Exception as e:
        print(f"Error querying registry: {e}")
        return os.path.join(os.environ.get('USERPROFILE', ''), 'Desktop')


def calculate_md5(file_path):
    hasher = hashlib.md5()
    with open(file_path, 'rb') as f:
        buf = f.read()
        hasher.update(buf)
    return hasher.hexdigest()


# 正则表达式匹配URL
def find_urls(text):
    url_pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\$\$,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
    return re.findall(url_pattern, text)
